# -*- coding: utf-8 -*-
# @Author : gongyu
# @Date   : 2019/4/4
# @File   : EC03_LoanDebtInterestCnt_2D.py
# @E-mail : gongyu@bbdservice.com

'''eof
name:贷款欠息次数
code:EC03_LoanDebtInterestCnt_2D
tableName:
columnName:
groups:企业征信模块
dependencies:EC_DSJ_2D
type:常用指标
dataSourceType:
eof'''

import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import datetime
import re


def isFloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x) >= 0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False


def convertDataType(data_value, data_type):
    """
    数据格式转换
    :param data_value:
    :param data_type: float/int/str/date_time
    :return:
    """

    return_data = None
    data_value = str(data_value)
    # float
    if data_type == 'float':
        try:
            return_data = float(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # int
    elif data_type == 'int':
        try:
            return_data = int(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # str
    elif data_type == 'str':
        try:
            return_data = str(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # date_time
    elif data_type == 'date_time':
        r = re.compile(r'\D+')
        try:
            return_data = datetime.datetime.strptime(data_value, '%Y.%m.%d').strftime('%Y-%m-%d')
        except:
            try:
                return_data = datetime.datetime.strptime(data_value, '%Y-%m-%d').strftime('%Y-%m-%d')
            except:
                try:
                    return_data = datetime.datetime.strptime(data_value, '%Y/%m/%d').strftime('%Y-%m-%d')
                except:
                    try:
                        data_value = r.sub('', data_value)
                        return_data = datetime.datetime.strptime(data_value, '%Y%m%d').strftime('%Y-%m-%d')
                    except:
                        return_data = None

    return return_data

def formatData(table_Name):
    """
    获取数据
    :param table_Name:字典keys
    :return:[{}]
    """
    try:
        data = EC_DSJ_2D["data"].get(table_Name)
        if data is None:
            return None
        elif data == "" or (isinstance(data, list) and len(data) == 0):
            return [{}]
        else:
            return data
    except:
        return None


def EC03_LoanDebtInterestCnt():
    """
    "1.Factor1=信息概要·未结清借贷交易汇总信息段(EB02A)-其他借贷交易分类汇总信息(EB02AH)·业务类型(EB02AD01)∈(1(中长期贷款),2(短期贷款),3(循环透支),4(贴现),0(合计))·count(逾期本金(EB02AJ04)>0 or逾期利息及其他(EB02AJ05)>0or逾期总额(EB02AJ03)>0)
    2.Factor2=信贷信息明细清单·欠息信息单元(ED03)·欠息类型(ED030D03)∈(1(表内),2(表外))·count(欠息余额(ED030J01)>0)
    3.Factor3=借贷账户信息单元·基本信息段(ED01A)·账户活动状态(ED01AD01)==1(未结清) and 借贷账户类型(ED01AD02) ∈(D1(非循环贷账户),D2(贴现账户),R1(循环贷账户),R4(循环额度下分账户)&还款表现信息段(ED01B)· count(余额(ED01BJ01)>0 and(逾期总额(ED01BJ04)>0or逾期本金(ED01BJ05)>0or逾期月数(ED01BS02)>0))
    4.FACTOR = MAX(FACTOR1,FACTOR2,FACTOR3)"

    :return:
    """

    null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

    EBB = formatData("EBB")            # 借贷交易汇总信息
    EDA = formatData("EDA")            # 借贷账户信息

    # Factor1
    if EBB is None:
        Factor1 = None
    elif EBB == [{}]:
        Factor1 = 0
    else:
        EB02 = EBB[0].get("EB02")
        if EB02 is None:
            Factor1 = 0
        elif EB02 in null_type_list:
            Factor1 = None
        else:
            EB02A = EB02[0].get("EB02A")     # 未结清借贷交易汇总信息段
            if EB02A is None:
                Factor1 = 0
            elif EB02A in null_type_list:
                Factor1 = None
            else:
                Factor1 = 0
                EB02AJ04 = EB02A[0].get("EB02AJ04")           # 逾期本金
                EB02AJ05 = EB02A[0].get("EB02AJ05")           # 逾期利息及其他
                EB02AJ03 = EB02A[0].get("EB02AJ03")           # 逾期总额
                EB02AH = EB02A[0].get("EB02AH")               # 其他借贷交易分类汇总信息
                if EB02AJ04 in null_type_list and EB02AJ05 in null_type_list and EB02AJ03 in null_type_list:
                    pass
                else:
                    if EB02AH is None:
                        Factor1 = 0
                    elif EB02AH in null_type_list:
                        Factor1 = None
                    else:
                        Factor1 = 0
                        flag = False
                        for i in range(len(EB02AH)):
                            # 业务类型
                            EB02AD01 = EB02AH[i].get("EB02AD01")
                            if EB02AD01 in null_type_list:
                                pass
                            else:
                                flag = True
                                if convertDataType(EB02AD01, 'str') in ['1', '2', '3', '4'] and \
                                    ((isFloat(EB02AJ04) and convertDataType(EB02AJ04, 'float') > 0) or \
                                    (isFloat(EB02AJ05) and convertDataType(EB02AJ05, 'float') > 0) or \
                                        (isFloat(EB02AJ03) and convertDataType(EB02AJ03, 'float') > 0)):
                                    Factor1 = Factor1 + 1
                                else:
                                    pass
                        if not flag:
                            Factor1 = None

    # Factor2
    if EDA is None:
        Factor2 = None
    elif EDA == [{}]:
        Factor2 = 0
    else:
        ED03 = EDA[0].get("ED03")
        if ED03 is None:
            Factor2 = 0
        elif ED03 in null_type_list:
            Factor2 = None
        else:
            Factor2 = 0
            flag = False
            for i in range(len(ED03)):
                ED030D03 = ED03[i].get("ED030D03")     # 欠息类型
                ED030J01 = ED03[i].get("ED030J01")     # 欠息余额
                if ED030D03 in null_type_list or ED030J01 in null_type_list:
                    pass
                else:
                    flag = True
                    if convertDataType(ED030D03, 'str') in ['1', '2'] and \
                            isFloat(ED030J01) and convertDataType(ED030J01, 'float') > 0:
                        Factor2 = Factor2 + 1
                    else:
                        pass
            if not flag:
                Factor2 = None

    # Factor3
    if EDA is None:
        Factor3 = None
    elif EDA == [{}]:
        Factor3 = 0
    else:
        ED01 = EDA[0].get("ED01")
        if ED01 is None:
            Factor3 = 0
        elif ED01 in null_type_list:
            Factor3 = None
        else:
            result = []
            for i in range(len(ED01)):
                ED01A = ED01[i].get("ED01A")   # 基本信息段
                ED01B = ED01[i].get("ED01B")   # 还款表现信息段

                if ED01A is None or ED01B is None:
                    result.append(None)
                elif ED01B == "":
                    result.append(0)
                else:
                    ED01AD01 = ED01A[0].get("ED01AD01")   # 账户活动状态
                    ED01AD02 = ED01A[0].get("ED01AD02")   # 借贷账户类型

                    if ED01AD01 is None or ED01AD02 is None:
                        result.append(None)
                    else:
                        ED01BH = ED01B[0].get("ED01BH")   # 还款表现信息
                        if ED01BH is None:
                            result.append(0)
                        elif ED01BH in null_type_list:
                            result.append(None)
                        else:
                            tmp_result = []
                            flag = False
                            for j in range(len(ED01BH)):
                                ED01BJ01 = ED01BH[j].get("ED01BJ01")   # 余额
                                ED01BJ04 = ED01BH[j].get("ED01BJ04")   # 逾期总额
                                ED01BJ05 = ED01BH[j].get("ED01BJ05")   # 逾期本金
                                ED01BS02 = ED01BH[j].get("ED01BS02")   # 逾期月数

                                ED01BJ01Ture = False
                                moneyTure = False
                                # 余额
                                if ED01BJ01 in null_type_list:
                                    pass
                                else:
                                    if isFloat(ED01BJ01):
                                        flag = True
                                        if float(ED01BJ01) > 0:
                                            ED01BJ01Ture = True

                                # 逾期总额
                                if ED01BJ04 in null_type_list:
                                    pass
                                else:
                                    if isFloat(ED01BJ04):
                                        flag = True
                                        if float(ED01BJ04) > 0 \
                                            and ED01BJ01Ture:
                                            moneyTure = True
                                    else:
                                        pass
                                # 逾期本金
                                if ED01BJ05 in null_type_list:
                                    pass
                                else:
                                    if isFloat(ED01BJ05):
                                        flag = True
                                        if float(ED01BJ05) > 0 and ED01BJ01Ture:
                                            moneyTure = True
                                    else:
                                        pass

                                # 逾期月数
                                if ED01BS02 in null_type_list:
                                    pass
                                else:
                                    if isFloat(ED01BS02):
                                        flag = True
                                        if float(ED01BS02) > 0 \
                                            and ED01BJ01Ture:
                                            moneyTure = True
                                    else:
                                        pass

                                if not flag:
                                    tmp_result.append(None)
                                else:
                                    # 逻辑判断
                                    if convertDataType(ED01AD01, 'str') == '1' and \
                                            convertDataType(ED01AD02, 'str') in ['D1', 'D2', 'R1', 'R4'] \
                                            and moneyTure:
                                            tmp_result.append(1)
                                    else:
                                        tmp_result.append(0)

                            tmp_result = filter(lambda x:x is not None, tmp_result)
                            if len(tmp_result) == 0:
                                result.append(None)
                            else:
                                result.append(sum(list(tmp_result)))

            result = filter(lambda x:x is not None, result)
            if len(result) == 0:
                Factor3 = None
            else:
                Factor3 = sum(list(result))


    if Factor1 is None and Factor2 is None and Factor3 is None :
        return u'缺失值'
    else:
        if Factor1 is None:
            Factor1 = 0
        if Factor2 is None:
            Factor2 = 0
        if Factor3 is None:
            Factor3 = 0

        Factor = max(Factor1, Factor2, Factor3)
        return Factor

# if __name__ == "__main__":
#     import json
#     with open(r'C:\Users\zdr\Desktop\samples\EC_DSJ_2D.json') as ff:
#         EC_DSJ_2D = json.loads(ff.read())
#     aa = EC03_LoanDebtInterestCnt()
#     print(aa)
result = EC03_LoanDebtInterestCnt()
